﻿using System;
using System.Collections.Generic;
using System.Text;
using GroupChat2013.Entity;
using System.Data;

namespace GroupChat2013.Data
{
    /// <summary>
    /// 最近聊天信息存储类
    /// </summary>
    public class RecChatRepository : BaseRepository
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public RecChatRepository(string dbPath)
            : base(dbPath, "t_RecChat")
        {

        }

        protected override void CreateTable()
        {
            //ChatType 1:私聊 2:群聊
            string cmdText = @"CREATE TABLE " + TableName +
                " (Id integer primary key autoincrement,ChatId varchar(64),ChatType integer,ChatName nvarchar(64),NickName nvarchar(64), HeadUrl nvarchar(64),CreateTime datetime);";
            SQLiteHelper.ExecuteNonQuery(DBPath, cmdText);
        }

        /// <summary>
        /// 获取最近聊天对象信息
        /// </summary>
        /// <returns></returns>
        public List<RecChatInfo> GetRecChatInfos(int count)
        {
            string cmdText = @"SELECT r.* FROM 
                            (SELECT  ChatId,MAX(CreateTime) AS CreateTime FROM " + TableName +
                           " group by ChatId  order by CreateTime desc LIMIT " + count + ") A INNER JOIN  " + TableName + " R  ON A.ChatId=R.ChatId AND A.CreateTime=R.CreateTime";

            List<RecChatInfo> result = new List<RecChatInfo>();
            var cmd = SQLiteHelper.CreateCommand(DBPath, cmdText);
            using (IDataReader reader = SQLiteHelper.ExecuteReader(cmd, cmdText, null))
            {
                while (reader.Read())
                {
                    result.Add(new RecChatInfo()
                    {
                        Id = reader.GetInt32(reader.GetOrdinal("Id")),
                        ChatId = reader.GetString(reader.GetOrdinal("ChatId")),
                        ChatName = reader.GetString(reader.GetOrdinal("ChatName")),
                        NickName = reader.GetString(reader.GetOrdinal("NickName")),
                        ChatType = (ChatType)Enum.Parse(typeof(ChatType), (reader.GetInt32(reader.GetOrdinal("ChatType"))).ToString()),
                        CreateTime = reader.GetDateTime(reader.GetOrdinal("CreateTime")),
                        HeadUrl = reader.GetString(reader.GetOrdinal("HeadUrl"))
                    });
                }
            }
            return result;
        }

        /// <summary>
        /// 添加最近聊天对象
        /// </summary>
        /// <param name="recLoginInfo"></param>
        public void AddRecChatInfo(RecChatInfo recChatInfo)
        {
            if (recChatInfo == null)
                return;

            if (IsAddToday(recChatInfo.ChatId))
            {
                return;
            }

            string cmdText = @"INSERT INTO " + TableName + @" (ChatId, ChatName,NickName, ChatType, HeadUrl, CreateTime) 
                                VALUES (@ChatId, @ChatName, @NickName, @ChatType, @HeadUrl, @CreateTime)";

            SQLiteHelper.ExecuteNonQuery(DBPath, cmdText,
                                         recChatInfo.ChatId,
                                         recChatInfo.ChatName,
                                         recChatInfo.NickName,
                                         (int)recChatInfo.ChatType,
                                         recChatInfo.HeadUrl,
                                         DateTime.Now);
        }

        /// <summary>
        /// 根据用户名查询用户是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private bool IsAddToday(string chatId)
        {
            string cmdText = "SELECT count(*) FROM " + TableName + " where ChatId=@chatId and date(createtime) ==date('now')";
            object data = SQLiteHelper.ExecuteScalar(DBPath, cmdText, chatId);
            return Convert.ToInt32(data) > 0;
        }
    }
}
